package com.iteaj.iot.client.proxy;

import com.iteaj.iot.client.ClientProperties;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.network.client.ClientComponent;
import com.iteaj.network.codec.adapter.LengthFieldBasedFrameMessageDecoderAdapter;
import com.iteaj.network.proxy.ProxyClientMessage;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandler;

import java.nio.ByteOrder;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class ProxyClient extends TcpSocketClient {

    private String deviceSn;

    public ProxyClient(ClientComponent clientComponent, ClientProperties.ClientProxy config) {
        super(clientComponent, config);
        this.deviceSn = UUID.randomUUID().toString();
    }

    @Override
    protected ChannelInboundHandler getClientProtocolDecoder() {
        ClientProperties.ClientProxy config = (ClientProperties.ClientProxy) getConfig();
        return new LengthFieldBasedFrameMessageDecoderAdapter(ByteOrder.LITTLE_ENDIAN, config.getMaxFrameLength()
                , 0, 4, 0, 4, true);
    }

    /**
     * 连接成功之后发送心跳包
     * @param future
     */
    @Override
    public void successCallback(ChannelFuture future) {
        ClientProperties.ClientProxy config = (ClientProperties.ClientProxy) getConfig();
        future.channel().eventLoop().scheduleAtFixedRate(() -> {
            try {
                new ProxyClientProtocol(ProxyClientMessage.heart(this.deviceSn)).timeout(0).request();
            } catch (Exception e) {
                logger.error("代理客户端心跳请求异常", e);
            }
        }, 10, config.getHeartPeriod(), TimeUnit.SECONDS);
    }

    public String getDeviceSn() {
        return deviceSn;
    }
}
